﻿using PMS.SANY.IBusiness;
using PMS.SANY.Models;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using PMS.SANY.Util;

namespace PMS.SANY.Api
{
    public class Operator : IOperator
    {
        private IServiceProvider SvcProvider { get; set; }
        public Operator(IServiceProvider svcProvider)
        {
            this.SvcProvider = svcProvider;
            var httpContextAccessor = this.SvcProvider.GetRequiredService<IHttpContextAccessor>();
            this.UserId = httpContextAccessor?.HttpContext?.User.Claims.Where(w => w.Type == "userId").FirstOrDefault()?.Value;
            if (this.UserId.IsNullOrEmpty()) this.UserId = "0";
        }
        public string UserId { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<UserModel> GetCurUser()
        {
            var cacheSvc = this.SvcProvider.GetRequiredService<IDistributedCache>();
            var cacheKey = $"Operator:{this.UserId}";
            var model = await cacheSvc.GetAsync<UserModel>(cacheKey);
            if (model != null) return model;
            var userSvc = this.SvcProvider.GetRequiredService<ISys_UserBusiness>();
            var entity = await userSvc.GetAsync(this.UserId);
            if (entity == null) throw new Exception("用户不存再");
            model = new UserModel()
            {
                Id = entity.Id,
                Name = entity.Name,
                UserName = entity.UserName
            };
            await cacheSvc.SetAsync(cacheKey, model, TimeSpan.FromDays(1));
            return model;
        }
    }
}
